<script setup lang="ts">
import { computed, onBeforeUnmount, onMounted, ref, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { message } from 'ant-design-vue';
import {
  CloseCircleOutlined,
  CloudUploadOutlined,
  ColumnHeightOutlined,
  ExclamationCircleOutlined,
  FileDoneOutlined,
  LeftOutlined,
  LoadingOutlined,
  PlusOutlined,
  SyncOutlined,
} from '@ant-design/icons-vue';
import DocumentUploadModal from '@/components/UploadFileResource/index.vue';
import UploadMediaModal from '@/components/UploadVedioResource/index.vue';
import BiliBiliLinkModal from '@/components/UploadUrlResource/index.vue'
import MoveResouce from "./ResourceMove.vue"
// import logo1 from '@/assets/1301.png';
// import logo2 from '@/assets/120.png';
// import logo3 from '@/assets/1401.png';
// import logo4 from '@/assets/117.png';
import { getIcon } from "@/api/assets/assets";
import { VueDraggable } from 'vue-draggable-plus';
import { RenameResourceApi, deleteResourceApi, fetchFlowStatus, fetchResourceApi, fetchUrlApi, handleResourceDropApi } from '@/api/Teacher/resourceApi';
import dayjs from 'dayjs';
import { creatSubchapterApi, deleteSubchapterApi } from '@/api/Teacher/subchapterApi';
import { fetchCoursesApi } from '@/api/Teacher/courseApi';
import MoveFolderModal from './SubChapterMove.vue'

const logo1 = ref<string>("");
const logo2 = ref<string>("");
const logo3 = ref<string>("");
const logo4 = ref<string>("");

const fetchIcon = async () => {
  try {
    const data = await getIcon(['1301.png', '120.png', '1401.png', '117.png']);
    logo1.value = data['1301.png'];
    logo2.value = data['120.png'];
    logo3.value = data['1401.png'];
    logo4.value = data['117.png'];
  }
  catch (error) {
    console.error('API 调用错误:', error);
  }
};

const formatDate = (date: any) => {
  return dayjs(date).format('YYYY-MM-DD');
};
const router = useRouter();
const route = useRoute();
const loading = ref(false);
// const modalVisible = ref(false);
const nameVisible = ref(false);
// const newChapterName = ref('');
const newName = ref('');
const data = ref<any[]>([]);
const courseId = ref('');
const searchValue = ref('');
const sortId = ref<number>(0);
const reName = ref('');
const check = ref(false);
const isMove = ref(false);
const selectedItem = ref<any>(null);
const uploadAudioVideoModalVisible = ref(false);
const uploadFileModalVisible = ref(false);
const uploadUrlModalVisible = ref(false);
const deleteConfirmVisible = ref(false);
const deleteItemTmp = ref<any>(null);
const resourceIdForNow = ref('');
const FolderModalVisible = ref(false);
const newChapterName = ref('');
const deleteFolderConfirmVisible = ref(false);
const deleteFolderItemTmp = ref<any>(null);
const Url = ref('');
const selectCourseFileId = ref('')
const selectedSourceId = ref('')
const selectedType = ref('')
const isFolderMove = ref(false)
const selectSectionId = ref('')
const courseList = ref<{ [key: string]: string }[]>([]);
const judgeStatus = ref(true);

const getStatusIcon = (status: string | undefined) => {
  switch (status) {
    case '资源':
      return logo1.value;
    case '音视频资源':
      return logo2.value;
    case '网页资源':
      return logo3.value;
    default:
      return logo4.value;
  }
};
// 移动模态框
const setMove = (value: boolean) => {
  isMove.value = value;
};
// 获取courseId
const fetchCourseId = async () => {
  try {
    const matchedCourseFileId = (route.params.path as string).split('|')[0]
    const response = await fetchCoursesApi("");
    const courseData = response.data;
    const matchedCourse = courseData.find(
      (item: any) => item.courseFileId === matchedCourseFileId,
    );

    if (matchedCourse)
      courseId.value = matchedCourse.courseId; // 提取匹配的数据块中的 courseId
    // 为面包屑导航添加数据
    const courseName = matchedCourse.name;
    const coursePath = `/teacher/manage/chapter/${encodeURIComponent(matchedCourse.courseFileId)}%7C`;
    courseList.value.push({ [courseName]: coursePath });
  }
  catch (error) {
    console.error('获取courseId出错:', error);
    message.error('获取courseId出错，请刷新');
  }
}
const fetchResourceData = async (resourceIds: string[], index: number) => {
  try {
    if (index >= resourceIds.length - 1)
      return; // 递归终止条件：index 超过资源 ID 数组长度时停止

    const getResourceId = resourceIds[index];
    const resourceId = resourceIds[index + 1]; // 获取下一个资源 ID
    const response = await fetchResourceApi(getResourceId, "");
    const resourceData = response.data;
    const matchedResource = resourceData.find((item: any) => item.resourceId === resourceId);

    if (matchedResource) {
      const resourceName = matchedResource.name;
      const path = matchedResource.resourcePath;
      const updatedPath = path.split('/').slice(1).join('/');
      const finalPath = updatedPath.replace(/\//g, '|');
      const resourcePath = `/teacher/manage/chapter/${encodeURIComponent(finalPath)}`;
      courseList.value.push({ [resourceName]: resourcePath });

      // 递归调用时增加 index
      fetchResourceData(resourceIds, index + 1); // 增加 index，处理下一个 resourceId
    }
  }
  catch (error) {
    console.error('获取资源数据出错:', error);
  }
};

const processPath = (routeParamsPath: string) => {
  const resourceIds = routeParamsPath.split('|').filter(id => id !== '');
  fetchResourceData(resourceIds, 0); // 从第一个资源 ID 开始处理
};

// 触发移动模态框
const handleMove = (item: any) => {
  selectedSourceId.value = item.resourceId;
  selectedType.value = item.tag;
  isMove.value = true;
}
const setFolderMove = (value: boolean) => {
  isFolderMove.value = value;
};
const handleFolderMove = (item: any) => {
  isFolderMove.value = true;
  selectSectionId.value = item.resourceId
}

// 选择是文件夹还是资源的移动模态框
const MoveChoice = (item: any) => {
  if (item.tag === "文件夹")
    handleFolderMove(item);

  else
    handleMove(item);
}
const fetchCourseData = async (courseFileId: string | null, load: boolean, searchValue: string) => {
  try {
    check.value = false;
    loading.value = load;
    data.value = [];
    const response = await fetchResourceApi(courseFileId, searchValue);
    const studyData = response.data;
    sortId.value = studyData[studyData.length - 1].sortOrder;
    data.value = studyData;
    check.value = true;
  }
  catch (error) {
    check.value = true;
  }
  finally {
    loading.value = false; // 数据加载完毕后隐藏 Spin
  }
};

// 首次挂载时调用 fetchCourseData
onMounted(async () => {
  courseList.value = [];
  selectCourseFileId.value = (route.params.path as string).split('|')[0];
  resourceIdForNow.value = (route.params.path as string).split('|').slice(-2, -1)[0];
  await fetchCourseId();
  await fetchCourseData(resourceIdForNow.value, true, searchValue.value);
  await processPath((route.params.path as string));
  await fetchIcon();
});

// 监视 route.params.path, check 和 searchValue 的变化，定时轮询数据
let intervalId: number | undefined;
watch(
  () => route.params.path,
  async (newPath) => {
    courseList.value = [];
    resourceIdForNow.value = (newPath as string).split('|').slice(-2, -1)[0];
    selectCourseFileId.value = (route.params.path as string).split('|')[0];
    await fetchCourseId();
    await fetchCourseData(resourceIdForNow.value, true, searchValue.value);
    await processPath((route.params.path as string));
    await fetchIcon();
  },
);

watch([check, searchValue], ([newCheck, newSearchValue]) => {
  if (newCheck) {
    intervalId = window.setInterval(() => {
      fetchCourseData(resourceIdForNow.value, false, newSearchValue);
    }, 50000);
  }
  else {
    if (intervalId)
      clearInterval(intervalId);
  }
});

// 在组件卸载之前清除定时器
onBeforeUnmount(() => {
  if (intervalId)
    clearInterval(intervalId);
});

const FetchUrl = async (resourceId: string) => {
  const response = await fetchUrlApi(resourceId);
  Url.value = response.data;
}
// 定义处理点击的函数
const handleItemClick = (item: any) => {
  const path = item.resourcePath.replace(/\//g, "|").split('|').slice(1).join('|');
  router.push(`/teacher/manage/chapter/${path}`);
};
const handleWordClick = (item: any) => {
  const PreCourseId = courseId.value;
  const PreFolderId = (BigInt(PreCourseId) + BigInt(1)).toString();
  const resourceId = item.resourceId;
  const path = encodeURIComponent(item.resourcePath);
  const shareUrl = import.meta.env.VITE_LOCAL_IP
  const newTabUrl = `http://${shareUrl}/learn/previewdocument/${PreCourseId}/${PreFolderId}/${resourceId}/${path}`
  window.open(newTabUrl, '_blank');
}
const handleVideoClick = (item: any) => {
  const PreCourseId = courseId.value;
  const PreFolderId = (BigInt(PreCourseId) + BigInt(1)).toString();
  const resourceId = item.resourceId;
  const path = encodeURIComponent(item.resourcePath);
  const shareUrl = import.meta.env.VITE_LOCAL_IP
  const newTabUrl = `http://${shareUrl}/learn/previewvideo/${PreCourseId}/${PreFolderId}/${resourceId}/${path}`
  window.open(newTabUrl, '_blank');
}
const handleURLClick = async (item: any) => {
  await FetchUrl(item.resourceId);
  window.open(Url.value, '_blank');
}
const handleItemClickIfNotResource = (element: { tag: string }) => {
  if (element.tag === '文件夹')
    handleItemClick(element);
  // if (element.tag === '资源')
  //   handleWordClick(element);
  // if (element.tag === '音视频资源')
  //   handleVideoClick(element);
  // if (element.tag === '网页资源')
  //   handleURLClick(element);
};
// 使用 lodash 的 debounce 对 handleItemClick 函数进行防抖处理
// const debouncedHandleItemClick = debounce(handleItemClick, 500);

// 定义处理返回的函数
const handleBackClick = async () => {
  const path = route.params.path as string;
  const countPipes = (path.match(/\|/g) || []).length;
  // 判断并执行不同逻辑
  if (countPipes === 1) {
    router.push(`/teacher/manage/course/course`);
  }
  else if (countPipes > 1) {
    const parentResourceId = path.replace(/\|[^|]*\|$/, '|');
    router.push(`/teacher/manage/chapter/${parentResourceId}`);
  }
};

// 使用 lodash 的 debounce 对 handleBackClick 函数进行防抖处理
// const debouncedHandleBack = debounce(handleBackClick, 500);

const handleDrop = async () => {
  try {
    const sortedIds = data.value.map(item => item.resourceId);
    const payload = { parentId: resourceIdForNow.value, sortedIds };
    await handleResourceDropApi(payload)
    message.success('资源顺序已更新');
    await fetchCourseData(resourceIdForNow.value, true, searchValue.value);
  }
  catch (error) {
    console.error('更新章节顺序时出错:', error);
    message.error('请求失败');
  }
};

// const handleNewChapter = () => {
//   modalVisible.value = true;
// };
// const handleModalCancel = () => {
//   modalVisible.value = false;
// };
// const handleModalOk = async () => {
//   try {
//     const response = await api.post('/java/StudySpaceTeacher/newcreateChapter', null, {
//       params: {
//         courseFile_id: pid.value,
//         file_name: newChapterName.value,
//         sort_order: sortId.value,
//       },
//     });
//     if (response.data.code === 1) {
//       message.success('章节创建成功');
//       modalVisible.value = false;
//       newChapterName.value = '';
//       await fetchCourseData(pid.value, true, searchValue.value);
//     }
//     else {
//       message.error('章节创建失败');
//     }
//   }
//   catch (error) {
//     console.error('Error creating chapter:', error);
//     message.error('请求失败');
//   }
// };

// 设置是否展示删除模态框
const setDeleteConfirmVisible = (visible: boolean) => {
  deleteConfirmVisible.value = visible;
};
const handleDelete = async (item: any) => {
  setDeleteConfirmVisible(false)
  try {
    await deleteResourceApi(item.resourceId, item.tag);
    message.success('课程文件删除成功');
    await fetchCourseData(resourceIdForNow.value, true, searchValue.value);
  }
  catch (error) {
    console.error('删除课程文件时出错:', error);
    message.error('请求失败');
  }
};

const showDeleteConfirm = (item: any) => {
  deleteItemTmp.value = item;
  setDeleteConfirmVisible(true);
};
const handleSearch = async () => {
  await fetchCourseData(resourceIdForNow.value, true, searchValue.value);
}

// 设置选中的 item 并显示模态框
const handleNewName = (item: any) => {
  selectedItem.value = item;
  nameVisible.value = true;
};

// 关闭模态框
const handleNewNameCancel = () => {
  nameVisible.value = false;
};

// 确定并发送更新请求
const handleNewNameOk = async () => {
  nameVisible.value = false;
  reName.value = selectedItem.value.resourceId;

  try {
    await RenameResourceApi(reName.value, newName.value, selectedItem.value.tag)
    message.success('更改成功');
    // 重新获取数据，假设有 fetchCourseData 函数
    await fetchCourseData(resourceIdForNow.value, true, searchValue.value);
  }
  catch (error) {
    message.error('请求失败');
    console.error('更改名称时发生错误:', error);
  }
  finally {
    newName.value = '';
  }
};

// 设置模态框的显示状态
const setUploadAudioVideoModalVisible = (visible: boolean) => {
  uploadAudioVideoModalVisible.value = visible;
};

const setUploadFileModalVisible = (visible: boolean) => {
  uploadFileModalVisible.value = visible;
};

const setUploadUrlModalVisible = (visible: boolean) => {
  uploadUrlModalVisible.value = visible;
};
const handleUploadFileModalCancel = () => {
  uploadFileModalVisible.value = false;
};
const handleUploadAudioVideoModalCancel = () => {
  uploadAudioVideoModalVisible.value = false;
};
const handleUplodaUrlModalCancel = () => {
  uploadUrlModalVisible.value = false;
}
// 判断流量限制
const judgeFlowControl = async () => {
  try {
    const response = await fetchFlowStatus(); // 假设 fetchFlowStatus 是一个获取数据的 API 方法
    const status = response.data;

    // 判断所有限制器是否都为 true
    if (
      status.UploadRateLimiter === true
      && status.HandleRateLimiter === true
      && status.VideoRateLimiter === true
    )
      judgeStatus.value = true;
    else
      judgeStatus.value = false;
  }
  catch (error) {
    console.error("Error fetching flow status:", error);
  }
};
// 菜单点击事件
const handleMenuClick = async ({ key }: { key: string }) => {
  // 调用 judgeFlowControl 检查状态
  await judgeFlowControl();

  if (judgeStatus.value) {
    // 状态为 true 时，根据 key 打开对应模态框
    if (key === '1')
      setUploadAudioVideoModalVisible(true);
    else if (key === '2')
      setUploadFileModalVisible(true);
    else if (key === '3')
      setUploadUrlModalVisible(true);
  }
  else {
    message.warning({
      content: "当前加工文件过多，请稍后再上传",
      duration: 3,
    });
  }

  judgeStatus.value = true;
};

// 新建章节模态框
const handleNewChapter = () => {
  FolderModalVisible.value = true;
};
const handleNewChapterModalCancel = () => {
  FolderModalVisible.value = false;
};
const handleNewChapterModalOk = async () => {
  FolderModalVisible.value = false;
  try {
    await creatSubchapterApi(resourceIdForNow.value, newChapterName.value, sortId.value)
    message.success('章节创建成功');
    newChapterName.value = '';
    await fetchCourseData(resourceIdForNow.value, true, searchValue.value);
  }
  catch (error) {
    console.error('Error creating chapter:', error);
    message.error('请求失败');
  }
};

// 删除文件夹模态框
const setFolderDeleteConfirmVisible = (visible: boolean) => {
  deleteFolderConfirmVisible.value = visible;
};
const handleFolderDelete = async (item: any) => {
  try {
    setFolderDeleteConfirmVisible(false)
    await deleteSubchapterApi(courseId.value, item.resourceId)
    message.success('课程文件删除成功');
    await fetchCourseData(resourceIdForNow.value, true, searchValue.value);
  }
  catch (error) {
    console.error('删除课程文件时出错:', error);
    message.error('请求失败');
  }
};
const showFolderDeleteConfirm = (item: any) => {
  deleteFolderItemTmp.value = item;
  setFolderDeleteConfirmVisible(true);
}
const deleteClickToChoose = (element: any) => {
  if (element.tag === '文件夹')
    showFolderDeleteConfirm(element);
  else if (element.tag)
    showDeleteConfirm(element);
};
</script>

<template>
  <div class="courseManager">
    <a-spin :spinning="loading" size="large">
      <div class="controlc">
        <h2 class="title">
          我的课程
        </h2>
        <!-- <a-space class="actions">
          <a-dropdown :trigger="['click']">
            <template #overlay>
              <a-menu @click="handleMenuClick">
                <a-menu-item key="1">
                  <span>音视频</span>
                </a-menu-item>
                <a-menu-item key="2">
                  <span>文档</span>
                </a-menu-item>
                <a-menu-item key="3">
                  <span>网页</span>
                </a-menu-item>
              </a-menu>
            </template>
            <a-button class="actionButton">
              <CloudUploadOutlined />
              上传资源
            </a-button>
          </a-dropdown>
        </a-space> -->
      </div>
      <div class="controls">
        <a-input-search
          v-model:value="searchValue"
          placeholder="搜索"
          class="search"
          enter-button
          @search="handleSearch"
        />
      </div>

      <div>
        <a-button type="default" @click="handleBackClick">
          <template #icon>
            <LeftOutlined />
          </template>
          返回上一级
        </a-button>
      </div>

      <div style="display: flex; justify-content: space-between;">
        <a-breadcrumb style="margin-top: 0.8rem; font-size: 1rem">
          <a-breadcrumb-item>
            <router-link to="/teacher/manage/course/course" class="h-full">
              课程
            </router-link>
          </a-breadcrumb-item>
          <template v-for="(item, index) in courseList" :key="index">
            <a-breadcrumb-item>
              <router-link :to="Object.values(item)[0]" class="h-full">
                {{ Object.keys(item)[0] }}
              </router-link>
            </a-breadcrumb-item>
          </template>
        </a-breadcrumb>
        <div>
          <a-button type="primary" style="margin-right: 1.875rem;font-size: 1rem;" @click="handleNewChapter">
            <template #icon>
              <PlusOutlined />
            </template>
            新建文件夹
          </a-button>
          <a-dropdown :trigger="['click']">
            <template #overlay>
              <a-menu @click="handleMenuClick">
                <a-menu-item key="1">
                  <span>音视频</span>
                </a-menu-item>
                <a-menu-item key="2">
                  <span>文档</span>
                </a-menu-item>
                <a-menu-item key="3">
                  <span>网页</span>
                </a-menu-item>
              </a-menu>
            </template>
            <a-button type="primary" style="margin-right: 1.875rem;font-size: 1rem;">
              <template #icon>
                <CloudUploadOutlined />
              </template>
              上传资源
            </a-button>
          </a-dropdown>
        </div>
      </div>

      <div class="listContainer">
        <div class="listHeader">
          <span style="min-width:34.375rem; font-size: 1rem; color: #4f4f44;">名称</span>
          <span style="min-width:20.625rem; font-size: 1rem; color: #4f4f44;">上传状态</span>
          <span style="min-width:20rem; font-size: 1rem; color: #4f4f44;">创建时间</span>
          <span style="min-width:18.75rem; font-size: 1rem; color: #4f4f44;">操作</span>
          <span style="min-width:6.25rem; font-size: 1rem; color: #4f4f44;">排序</span>
        </div>
        <transition-group name="flip-list" tag="div">
          <VueDraggable
            :key="1"
            v-model="data"
            @end="handleDrop"
          >
            <!-- 使用默认 slot 来渲染 draggable 内容 -->
            <div v-for="element in data" :key="element.resourceId">
              <a-list-item class="listItem" @click="handleItemClickIfNotResource(element)">
                <!-- 第一列 -->
                <div style="min-width: 34.375rem;" class="courseInfo">
                  <img
                    v-if="element.tag !== '文件夹'"
                    :src="getStatusIcon(element.webName ? '网页' : element.tag)"
                    alt="课程图标"
                    class="icon"
                  >
                  <span class="courseText">{{ element.name || element.webName }}</span>
                </div>

                <!-- 第二列 -->
                <div style="min-width: 20.625rem;">
                  <template v-if="element.tag === '资源'">
                    <!-- 文档加工状态 -->
                    <template
                      v-if="!element.ossWriteStatus && !element.ragCompleteStatus && !element.smartTextStatus && !element.handleCompleteStatus"
                    >
                      <LoadingOutlined spin style="color: #FFB64C; font-size: 1.25rem; margin-right: 0.5rem;" />
                      <span style="font-size: 1.125rem;">上传中</span>
                    </template>
                    <template
                      v-else-if="element.ossWriteStatus && !element.ragCompleteStatus && !element.smartTextStatus && !element.handleCompleteStatus"
                    >
                      <SyncOutlined style="color: #84E17E; font-size: 1.25rem; margin-right: 0.5rem;" />
                      <span style="font-size: 1.125rem;">加工中</span>
                    </template>
                    <template
                      v-else-if="element.ossWriteStatus && element.ragCompleteStatus && !element.smartTextStatus && !element.handleCompleteStatus"
                    >
                      <SyncOutlined style="color: #84E17E; font-size: 1.25rem; margin-right: 0.5rem;" />
                      <span style="font-size: 1.125rem;">加工中</span>
                    </template>
                    <template
                      v-else-if="element.ossWriteStatus && element.ragCompleteStatus && element.smartTextStatus && element.handleCompleteStatus"
                    >
                      <FileDoneOutlined style="color: #868AF6; font-size: 1.25rem; margin-right: 0.5rem;" />
                      <span style="font-size: 1.125rem;">加工成功</span>
                    </template>
                    <template
                      v-else-if="element.handleCompleteStatus && (!element.ossWriteStatus || !element.ragCompleteStatus || !element.smartTextStatus)"
                    >
                      <CloseCircleOutlined style="color: #FF4D4F; font-size: 1.25rem; margin-right: 0.5rem;" />
                      <span style="font-size: 1.125rem;">加工失败</span>
                    </template>
                  </template>

                  <!-- 音视频加工状态 -->
                  <template v-else-if="element.tag === '音视频资源'">
                    <template
                      v-if="element.ossWriteStatus && element.transcriptionComplete && element.transcriptionCompleteStatus"
                    >
                      <FileDoneOutlined style="color: #868AF6; font-size: 1.25rem; margin-right: 0.5rem;" />
                      <span style="font-size: 1.125rem;">加工成功</span>
                    </template>
                    <template v-else-if="!element.transcriptionComplete && !element.transcriptionCompleteStatus">
                      <SyncOutlined style="color: #84E17E; font-size: 1.25rem; margin-right: 0.5rem;" />
                      <span style="font-size: 1.125rem;">加工中</span>
                    </template>
                    <template v-else>
                      <CloseCircleOutlined style="color: #FF4D4F; font-size: 1.25rem; margin-right: 0.5rem;" />
                      <span style="font-size: 1.125rem;">加工失败</span>
                    </template>
                  </template>
                  <!-- <template v-else-if="element.tag === '网页资源'">
                    <FileDoneOutlined style="color: #868AF6; font-size: 1.25rem; margin-right: 0.5rem;" />
                    <span style="font-size: 1.125rem;">加工成功</span>
                  </template> -->
                </div>

                <!-- 第三列 -->
                <span style="min-width: 19.375rem; font-size: 1.125rem;">
                  {{ formatDate(element.createdAt) || '未知时间' }}
                </span>

                <!-- 操作列 -->
                <div style="min-width: 20rem;font-size: 1rem; display: flex; align-items: center;">
                  <a
                    href="#edit"

                    style="border-right: 1px solid #ccc; padding-right: 1rem; margin-right: 1rem;"
                    @click.stop.prevent="handleNewName(element)"
                  >
                    <span>编辑</span>
                  </a>
                  <a
                    href="#move"

                    style="border-right: 1px solid #ccc; padding-right: 1rem; margin-right: 1rem;"
                    @click.stop.prevent="() => MoveChoice(element)"
                  >
                    <span>移动</span>
                  </a>
                  <a
                    href="#delete"
                    @click.stop.prevent="deleteClickToChoose(element)"
                  >
                    <span style="color: red;">删除</span>
                  </a>
                </div>

                <!-- 图标列 -->
                <div>
                  <ColumnHeightOutlined style="font-size: 1.25rem; color: #81838F;" />
                </div>
              </a-list-item>
            </div>
          </VueDraggable>
        </transition-group>
      </div>
    </a-spin>

    <!-- <a-modal
      v-model:visible="modalVisible"
      title="新建章节"
      @ok="handleModalOk"
      @cancel="handleModalCancel"
    >
      <a-input v-model="newChapterName" placeholder="请输入章节名称" />
    </a-modal> -->
    <a-modal
      v-model:open="nameVisible"
      title="重命名"
      ok-text="确定"
      cancel-text="取消"
      :body-style="{ height: 'auto' }"
      @ok="handleNewNameOk"
      @cancel="handleNewNameCancel"
    >
      <span style="font-size: 16px; color: #101010;">请输入新名字</span>
      <a-input
        v-model:value="newName"
        class="customInput"
        placeholder="请输入新名称"
      />
    </a-modal>
    <!-- 文档上传模态框 -->
    <DocumentUploadModal
      :visible="uploadFileModalVisible"
      :course-file-id="resourceIdForNow || 'default_course-file-id'"
      :course-id="courseId || 'default_course_id'"
      :sort-id="sortId || 0"
      :fetch-course-data="fetchCourseData"
      @close="handleUploadFileModalCancel"
    />

    <!-- 音视频上传模态框 -->
    <UploadMediaModal
      :visible="uploadAudioVideoModalVisible"
      :course-file-id="resourceIdForNow || 'default_course-file-id'"
      :course-id="courseId || 'default_course_id'"
      :sort-id="sortId || 0"
      :fetch-course-data="fetchCourseData"
      @close="handleUploadAudioVideoModalCancel"
    />

    <!-- 网页上传模态框 -->
    <BiliBiliLinkModal
      :visible="uploadUrlModalVisible"
      :course-file-id="resourceIdForNow || 'default_course-file-id'"
      :course-id="courseId || 'default_course_id'"
      :sort-id="sortId || 0"
      :fetch-course-data="fetchCourseData"
      @close="handleUplodaUrlModalCancel"
    />
  </div>
  <a-modal v-model:open="deleteConfirmVisible" width="550" closable centered>
    <p>您确定要删除所选中的内容吗？内容一旦被删除将不能恢复。</p>
    <template #title>
      <ExclamationCircleOutlined style="color: red;" />
      删除
    </template>

    <template #footer>
      <a-button key="back" class="delete-button" @click="setDeleteConfirmVisible(false)">
        取消
      </a-button>
      <a-button
        key="submit" type="danger" class="delete-button"
        style="background-color: #FF7575; border-color: #FF7575; color:#FFFFFF;"
        @click="handleDelete(deleteItemTmp)"
      >
        确定
      </a-button>
    </template>
  </a-modal>
  <MoveResouce
    :visible="isMove"
    :course-file-id="selectCourseFileId || 'default_course-file-id'"
    :course-id="courseId || 'default_course_id'"
    :resource-id="resourceIdForNow || 'default_resource-id'"
    :source-id="selectedSourceId || 'default_source-id'"
    :source-type="selectedType || 'default_type'"
    :fetch-course-data="fetchCourseData"
    @close="setMove(false)"
  />
  <a-modal
    v-model:open="FolderModalVisible"
    title="新建文件夹"
  >
    <template #footer>
      <a-button key="back" class="delete-button" @click="handleNewChapterModalCancel()">
        取消
      </a-button>
      <a-button key="submit" type="danger" class="delete-button" style="background-color: #1677ff; border-color: #1677ff; color:#FFFFFF;" @click="handleNewChapterModalOk()">
        确定
      </a-button>
    </template>
    <a-input v-model:value="newChapterName" placeholder="请输入章节名称" />
  </a-modal>

  <!-- 删除文件夹的模态框 -->
  <a-modal v-model:open="deleteFolderConfirmVisible" width="550" closable centered>
    <p>您确定要删除所选中的内容吗？内容一旦被删除将不能恢复。</p>
    <template #title>
      <ExclamationCircleOutlined style="color: red;" />
      删除
    </template>

    <template #footer>
      <a-button key="back" class="delete-button" @click="setFolderDeleteConfirmVisible(false)">
        取消
      </a-button>
      <a-button key="submit" type="danger" class="delete-button" style="background-color: #FF7575; border-color: #FF7575; color:#FFFFFF;" @click="handleFolderDelete(deleteFolderItemTmp)">
        确定
      </a-button>
    </template>
  </a-modal>
  <MoveFolderModal
    :is-visible="isFolderMove"
    :course-file-id="selectCourseFileId || 'default_course-file-id'"
    :course-id="courseId || 'default_course_id'"
    :resource-id="resourceIdForNow || 'default_resource-id'"
    :section-id="selectSectionId || 'default_section-id'"
    :fetch-course-data="fetchCourseData"
    @close="setFolderMove(false)"
  />
</template>

<style scoped>
.delete-button {
  font-size: 1rem;
  padding: 0px 1.25rem;
}

.courseManager {
  background-color: #fff;
  padding-right: 0px;
  height: calc(100vh - 100px);
  overflow-y: hidden;
  overflow-x: auto;

  .title {
    font-size: 20px;
    margin-bottom: 20px;
  }

  .controlc {
    display: flex;
    justify-content: space-between;
    margin-bottom: 20px;

    .actionButton {
      font-size: 16px;
      color: #fff;
      background-color: #6698ff;
      margin-right: 2rem;
      padding: 0rem 0.9375rem;
      padding-top: 0.5rem;
      padding-bottom: 2rem;
      border-radius: 0rem;
    }
  }

  .controls {
    display: flex;
    margin-bottom: 1.25rem;

    .search {
      width: 18.75rem;
    }
  }

  .listHeader {
    display: flex;
    font-weight: bold;
    padding: 15px 0;
    padding-right: 100px;
    background-color: rgb(255, 255, 255);
    border-bottom: 1px solid rgba(187, 187, 187, 1);
    position: sticky; /* 吸顶效果 */
    top: 0; /* 吸附在顶部 */
    z-index: 10; /* 确保它在其他内容之上 */
  }
  .listContainer {
  height: calc(100vh - 300px); /* 设置内容区高度，确保滚动效果 */
  overflow-y: auto;
  overflow-x: hidden;
}
  .customInput {
    margin-top: 15px;
    font-size: 16px;
    color: #101010;
  }

  .customInput::placeholder {
    color: #81838f;
    font-size: 16px;
  }

  .listItem {
    display: flex;
    border-bottom: 1px solid rgba(187, 187, 187, 1);
    align-items: center;
    padding: 1.25rem 0;
    cursor: pointer;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;

    &:hover {
      background-color: #fafafa;

      .actions {
        opacity: 1;
      }
    }

    .courseInfo {
      display: flex;
      align-items: center;

      .icon {
        width: 24px;
        height: 24px;
        margin-right: 10px;
      }

      .courseText {
        white-space: nowrap;
        font-size: 1.125rem;
        overflow: hidden;
        text-overflow: ellipsis; /* 溢出部分显示省略号 */
        display: inline-block; /* 确保元素是块状或内联块状，这样可以设置宽度 */
        max-width: 350px; /* 限制最大宽度为300px */
      }
    }

    .actions {
      display: flex;
      gap: 20px;
      opacity: 0; /* 默认隐藏 */
      transition: opacity 0.3s ease;
    }

    .updatedAt {
      text-align: right;
      min-width: 160px; /* 保证更新时间在足够宽度内显示 */
    }
  }

}
</style>
